package com.vizhuo.mobile.base;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vizhuo.client.base.AbstractReply;
import com.vizhuo.client.base.AbstractRequest;
import com.vizhuo.client.base.AbstractUrls;
import com.vizhuo.utils.JacksonUtil;

/**
 * @author YuanWenLong 作者 E-mail: yuanwenlong2010@163.com
 * @date 创建时间：2015年6月25日 下午6:22:00
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public abstract class AbstractServerController {
    private static Logger logger = LoggerFactory.getLogger(AbstractServerController.class);

    /**
     * 从HttpRequest中获取Request
     * 
     * @param <T>
     * @param request
     * @param clazz
     * @return
     */
    public <T extends AbstractRequest> T getRequestFromHttpRequest(HttpServletRequest request, Class<T> requestClass) {
        return JacksonUtil.toObject(getJsonFromRequest(request), requestClass);
    }

    public String getJsonFromRequest(HttpServletRequest request) {
        String json = request.getParameter(AbstractUrls.REQUEST_KEY);
        logger.debug("收到客户端请求：" + request.getRequestURL() + "?" + AbstractUrls.REQUEST_KEY + "=" + json);
        logger.debug("收到客户端请求,sessionId：" + request.getSession().getId());
        return json;
    }

    /**
     * 返回成功结果到view
     * 
     * @param <T>
     * @param response
     * @param reply
     */

    public <T extends AbstractReply> void returnJsonResult(HttpServletResponse response, T reply) {
        try {
            response.setContentType("application/json;charset=utf-8");
            String replyJson = JacksonUtil.toJson(reply);
            logger.debug("返回给客户端内容：(" + reply.getClass().getName() + ")" + replyJson);
            response.getWriter().write(replyJson);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
